import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import getters from "./getters";
import { menus } from "@/router/menu.config";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    collapsed: false,
    menuTree: menus //左侧导航数据
  },
  mutations: {
    collapsed(state, value) {
      state.collapsed = !!value;
    },
    menuTree(state, list) {
      state.menuTree = list || [];
    }
  },
  actions: {
    setCollapse({ commit }, value) {
      commit("collapsed", value);
    },
    setMenuTree({ commit }, list) {
      commit("menuTree", list);
      // return spaceApi
      //   .getSpaceList(payload)
      //   .then(res => {
      //     commit("menuTree", res.data);
      //   })
      //   .catch(() => {
      //     message.error("获取菜单列表失败");
      //   });
    }
  },
  modules: {
    ...loadModules()
  },
  getters: {
    ...getters
  },
  plugins: [
    createPersistedState({
      storage: window.sessionStorage
    })
  ]
});


/**
 * 动态加载 modules 中的vuex模块
 * @returns 
 */
function loadModules() {
  const modulesFiles = require.context("./modules", true, /\.(j|t)s$/i);
  const regx = /^\.\/(.*)\.\w+$/;
  const modules = modulesFiles.keys().reduce((modules, modulePath) => {
    const moduleName = modulePath.replace(regx, "$1");
    const value = modulesFiles(modulePath);
    modules[moduleName] = value.default;
    return modules;
  }, {});
  return modules || {};
}
